$(function() {
    var bdbServiceManage = {
		/* 初始数据 */
		defData: {
			pageSize: 20 // 每页分页数量.
		},

		/* 页面状态 */
		pageState: {
			search: '',
			page: 1,
		    modifiedId:'',
		  	noData: 'def', // search: 没有匹配的结果; def: 暂无记录.
			sort: {
				type: 'def', // 创建时间(def：默认; asc:正序; desc：倒序).
			    role: 'def'
			}
		},

	  	/* 添加后重置列表查询条件 */
	    resetPageState: function () {
		  	this.pageState = {
			  search: '',
			  page: 1,
			  noData: 'def', // search: 没有匹配的结果; def: 暂无记录.
			  sort: {
				type: 'def', // 创建时间(def：默认; asc:正序; desc：倒序).
				role: 'def'
			  }
			};
		  	this.list();
		},

	  	//添加服务器组
	  	addEvent: function() {
			var _this = this,
				addVerifyObj;

		    addVerifyObj = $('#bdb-server-add-form').validate({
				errorElement: "div",
				errorPlacement: function(error, element) {
					error.addClass("help-block");
					if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
						error.appendTo(element.parents(".bdb-vc"));
					} else {
						error.insertAfter(element);
					}
				},
				submitHandler: function(form, e) {
					e.preventDefault();
					_this.addSubmit(form);
				}
			});

			$('.bdb-add-servers').off('click').on("click", function() {
				$.post('/ServerGroup/addServerGroupInit', function(response) {
					if (response.code == 0) {
						bdbMain.mLRManag({mask: false, loading: false});
						_this.serverStatusChange(response.data.serverGroupType, response.data.serverGroupRole, addVerifyObj);
					} else {
						bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
					}
				});
			});
		},

	  	//服务器组性质切换事件
	  	serverStatusChange: function(type, role, verifyObj, list) {
			var addDialogEle = $('.bdb-dialog'),
				statusHtml = bdbMain.attr.selDefOption,
				roleHtml = bdbMain.attr.selDefOption;

			$('[name = "serviceStatus"]').off('change').on('change', function() {
				var typeVal = $(this).val();
			    $('[name="serviceRole"]').empty().append(bdbMain.attr.selDefOption);
				$.each(role, function(i, n) {
					if (typeVal == i) {
						$.each(n, function(j, v) {
							$('[name="serviceRole"]').append('<option value="' + v.server_role_id + '">' + v.role_name + '</option>');
						});
					}
				});

			});

			if (list) {
				$.each(type, function(i, n) {
					if (i == list.type) {
						statusHtml += '<option value="' + i + '" selected="selected">' + n + '</option>';
					} else {
						statusHtml += '<option value="' + i + '">' + n + '</option>';
					}
				});

				$.each(role, function(j, m) {
					$.each(m, function(k, v) {
						if (v.type == list.type) {
							if (v.server_role_id == list.server_role_id) {
							  roleHtml += '<option selected="selected" value="' + v.server_role_id + '">' + v.role_name + '</option>';
							}else{
							  roleHtml += '<option value="' + v.server_role_id + '">' + v.role_name + '</option>';
							}
						}
					});
				});

				addDialogEle.find('[name = "serviceStatus"]').html(statusHtml);
				addDialogEle.find('[name = "serviceRole"]').html(roleHtml);
				$(".bdbBlankEle").bdbDialog({
					ele: '#bdb-server-edit-dialog',
					formObj: verifyObj,
					form: $('#bdb-server-edit-form'),
					reset: false
				});
			} else {
				$.each(type, function(i, n) {
					statusHtml += '<option value="' + i + '">' + n + '</option>';
				});

				addDialogEle.find('[name = "serviceStatus"]').html(statusHtml);
				addDialogEle.find('[name = "serviceRole"]').html(roleHtml);
				$(".bdbBlankEle").bdbDialog({
					ele: '#bdb-server-add-dialog',
					formObj: verifyObj,
					form: $('#bdb-server-add-form'),
					reset: true
				});
			}
		},

	  	//提交添加的服务器组
	  	addSubmit: function(form) {
		  	var _this = this,
				form = $(form);

		  	if (!bdbMain.ajaxInfo.state) {
		  	  	bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
		  	  	return;
			}
			// 发送请求.
			bdbMain.ajaxInfo.state = 0; // 加锁.
			bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
			$.post('/ServerGroup/addServerGroup', {
			  	server_name: form.find("#servicesNameAdd").val(),
			  	server_code: form.find("#servicesCodeAdd").val(),
			  	server_role_id: form.find("#serviceRoleAdd").val(),
			  	description: form.find("#messageAdd").val(),
			  	status: form.find("#serviceStatusAdd").val()
			}, function(response) {
				if (response.code == 0) {
					$(".js-bdb-dialog-cancel").click();
					bdbMain.mLRManag({maskDown: 99, alert: {type: 1, msg: '添加成功.'}});
					_this.resetPageState();
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert:{type: 2, msg: response.msg}});
				}

			    bdbMain.ajaxInfo.state = 1; // 释放锁.
			});
		},

	  	/* 设置服务器组 */
	  	setEvent: function() {
			var _this = this,
				modifyVerifyObj;

			modifyVerifyObj = $('#bdb-server-edit-form').validate({
				errorElement: "div",
				errorPlacement: function (error, element) {
					error.addClass("help-block");
					if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
						error.appendTo(element.parents(".bdb-vc"));
					} else {
						error.insertAfter(element);
					}
				},
				submitHandler: function(form, e) {
					e.preventDefault();
					_this.modifySubmit(form);
				}
			});

			$.post('/ServerGroup/editServerGroupInit', {
			  	'server_group_id': _this.pageState.modifiedId
			}, function(response) {
				if (response.code == 0) {
					bdbMain.mLRManag({mask: false, loading: false});

					$('#servicesNameEdit').val(response.data.list.server_name);
					$('#servicesCodeEdit').val(response.data.list.server_code);
					$('#messageEdit').val(response.data.list.description);

					_this.serverStatusChange(response.data.serverGroupType, response.data.serverGroupRole, modifyVerifyObj, response.data.list);
				} else {
				  	bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
				}
			});
		},

	  	//提交修改服务器组
	  	modifySubmit: function(form) {
			var _this = this,
				form = $(form);

			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0; // 加锁.
			bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
			$.post('/ServerGroup/editServerGroup', {
			  	server_group_id: _this.pageState.modifiedId,
				server_name: form.find("#servicesNameEdit").val(),
				server_code: form.find("#servicesCodeEdit").val(),
				server_role_id: form.find("#serviceRoleEdit").val(),
				description: form.find("#messageEdit").val(),
				status: form.find("#serviceStatusEdit").val()
			}, function(response) {
				if (response.code == 0) {
					$(".js-bdb-dialog-cancel").click();
					bdbMain.mLRManag({maskDown: 99, alert: {type: 1, msg: '修改成功.'}});
				    _this.list({page: _this.pageState.page});
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert:{type: 2, msg: response.msg}});
				}

				bdbMain.ajaxInfo.state = 1; // 释放锁.
			});
		},

	  	//服务器组暂停或启用操作按钮
	    startupPauseEvent: function(dataID, dataStauts) {
		  	var _this = this,
				optCont = dataStauts == 1 ? '暂停' : '启用';

			bdbMain.confirm({
				textInfo: {
					content: '确定要' + optCont + '吗？',
					btn: {
						ok: optCont,
						cancel: '取消'
					}
				},
			  	note: true,
				callback: function(ele, params) {
					_this.startupPauseProc(ele, dataID, dataStauts);
				}
			});
		},

	  	//暂停或启用发送请求
		startupPauseProc: function(ele, dataID, dataStauts) {
		  	var _this = this;
			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0;
			$.post('/ServerGroup/changeStatus', {
				'server_group_id': dataID,
				'status': dataStauts,
				'description': ele.find('#bdb-confirm-note').val()
			}, function(res) {
				if (res.code == 0) {
				    _this.list({page: _this.pageState.page});
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 2, msg: res.msg}});
				}
			    bdbMain.ajaxInfo.state = 1;
				ele.hide();
				bdbMain.closeMask();
			});
		},

	  	//搜索
	  	searchEvent: function() {
			var _this = this,
				searchInputEle = $('.bdb-search-input');

			searchInputEle.off('focusin').on('focusin', '.search-text', function(e) {
				var _cThis = $(this),
					_btnEle = $(this).parent().find('span');

				if (!_btnEle.hasClass('search-clear')) {
				    _cThis.animate({width: '240px'}, 500);
					_btnEle.animate({ left : 240 }, 500, function() {
						_btnEle.removeClass('search-gray').addClass('search-blue');
					});
				}
			});

			searchInputEle.off('click').on('click', 'span', function(e) {
			    var left = parseInt($(this).css('left'));
				if ($(this).hasClass('search-blue') && left > 0) {
					_this.pageState.search = searchInputEle.find('.search-text').val();
				  	_this.pageState.noData = 'search';
				    $(this).removeClass('search-blue').addClass('search-clear');
					_this.list();
				} else if(left > 0){
				    _this.pageState.search = '';
				    _this.pageState.noData = 'def';
					searchInputEle.find('.search-text').val('');
					$(this).removeClass('search-clear').addClass('search-blue');
				    _this.list();
				}
			});
		},

	  	//排序-性质/角色
	  	sortEvent: function () {
			var _this = this;
			$('.bdb-table-header').off('click.sortEvent').on('click.sortEvent', function (e) {
			  	var sortId = $(e.target).attr('id');
			  	switch (sortId) {
					case 'bdb-servers-status' :
						if (_this.pageState.sort.type == 'asc') {
							_this.pageState.sort.type = 'desc';
						}else {
							_this.pageState.sort.type = 'asc';
						}
					    break;
					case 'bdb-server-role' :
						if (_this.pageState.sort.role == 'asc') {
							_this.pageState.sort.role = 'desc';
						}else {
							_this.pageState.sort.role = 'asc';
						}
						break;
					default:
						return;
				}

			    _this.list({page: _this.pageState.page});
			});
		},

      	/* 获取列表数据 */
		listEvent: function() {
			var _this = this;
			$('.bdb-list').off('click').on('click', '.bdb-option-btn', function(e) {
				var ele = $(e.target),
					dataId = ele.parents('.bdb-list-row').attr('data-id'),
					dataStauts = ele.parents('.bdb-list-row').attr('data-status');

				if (ele.hasClass('server-set')) {
				    _this.pageState.modifiedId = dataId;
				  	_this.setEvent();

				} else if (ele.hasClass('server-start-pause')) {
				  	_this.startupPauseEvent(dataId, dataStauts);
				}
			});
		},

		list: function(obj) {
			var _this = this,
				obj = obj || {page: 1};

			_this.pageState.page = obj.page;
			bdbMain.mLRManag({mask: false, partMask: true});

			$.post('/ServerGroup/listServerGroup', {
			    pageNumber: _this.pageState.page,
				pageSize: _this.defData.pageSize,
				query: _this.pageState.search,
				orderBy: _this.pageState.sort
			}, function(response) {
				var totalRowCnt = 0;
				if (response.code == 0) {
					bdbMain.mLRManag({partMask: false, loading: false});
					var listHtml = _this.listProc(response.data);
					totalRowCnt = response.data.totalCount;
				    _this.listNull(totalRowCnt);
					$('.bdb-list').html(listHtml);

					//分页插件展示
					$('#js-bdb-creatPage').bdbPagination({
						totalRowCnt: totalRowCnt,
						currentPage: _this.pageState.page,
						pageSize: _this.defData.pageSize
					});
					$('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}',totalRowCnt));
				} else {
				    bdbMain.mLRManag({partMask: false, loading: false, alert: {type: 2, msg: response.msg}});
				}


			});

		},
	  	listProc: function(data) {
			var tpl = '';
			$.each(data.list, function(index, value) {
			  	var  imgSrc = '',
					 optText = '',
					 statusObj= ['存储','缓存','其他'];

			  	if(value.status == 1) {
					imgSrc = "point-green.svg";
					optText = '暂停'
				}  else{
				  	imgSrc = "point-gray.svg";
				  	optText = '启用'
				}

				tpl += '<div class="bdb-list-row" data-id="' + value.server_group_id + '" data-status = "' + value.status + '">\
						  <div class="bdb-mx-w-col-1"><img src="/static/imgs/global/' + imgSrc +'" alt=""></div>\
						  <div class="bdb-mx-w-col-2 bdb-ellipsis">' + value.server_group_id + '</div>\
						  <div class="bdb-mx-w-col-3 bdb-ellipsis">' + value.server_name + '</div>\
						  <div class="bdb-mx-w-col-4 bdb-ellipsis">' + value.server_code + '</div>\
						  <div class="bdb-mx-w-col-5 bdb-ellipsis">' + statusObj[value.type-1] + '</div>\
						  <div class="bdb-mx-w-col-6 bdb-ellipsis">' + value.role_name + '</div>\
						  <div class="bdb-mx-w-col-7 bdb-ellipsis">' + value.description + '</div>\
						  <div class="bdb-mx-w-col-8">\
						  <div class="bdb-option-btn  bdb-p-r bdb-mgn-t-10">\
						  <a class="bdb-mgn-l--1 server-set" href="javascript:void(0);">设置</a>\
						  <div class="v-line-ffa007"></div>\
						  <a class="bdb-mgn-l--1 ip-band-page" href="listIP/'+ value.server_group_id + '">绑定/释放</a>\
						  <div class="v-line-ffa007"></div>\
						  <a class="bdb-mgn-l--1 server-start-pause" href="javascript:void(0);">'+optText+'</a>\
						  </div>\
						  </div>\
						  </div>';
			});
			return tpl;
		},
		listNull: function(totalRowCnt) {
			var noResult = $('.bdb-no-result'),
				noSearchRecord = $('.bdb-no-search-record');

			if (totalRowCnt <= 0) {
				if (this.pageState.noData == 'search') { // 查询无结果
					noResult.hide();
					noSearchRecord.show();
				} else { // 暂无记录.
					noResult.show();
					noSearchRecord.hide();
				}
			} else {
				noResult.hide();
				noSearchRecord.hide();
			}
		},

	  	//加载分页
	  	pageEvent: function() {
			var _this = this;
			$('.bdb-creatPage').off('click').on('click', '.bdb-pagination', function(e) {
			  	e.preventDefault();
				var page = parseInt($(e.target).text());
				if(!isNaN(page)) {
				   _this.list({page: page});
				}
			});
		},

      	contentSizeResize: function() {
			$(window).resize(function() {
			  	$('.bdb-list').bdbScreenH(1);
			});
		},

        //初始化
        init: function () {
      	    var _this = this;

      	    _this.list();
      	    _this.addEvent();
      	    _this.listEvent();
      	    _this.searchEvent();
      	    _this.pageEvent();
      	    _this.sortEvent();
      	    _this.contentSizeResize();

		  	$('.bdb-list').bdbScreenH(1);
	    }
	};

  	bdbServiceManage.init();
});
